#include "SingleLock.h"
#include "CriticalSection.h"

namespace cupid
{
SingleLock::SingleLock(SyncObject* pObject, BOOL bInitialLock)
{
	ASSERT(pObject != NULL);

	m_pObject = pObject;
	m_hObject = pObject->m_hObject;
	m_bAcquired = FALSE;

	if (bInitialLock)
		Lock();
}
SingleLock::~SingleLock()
{ 
	Unlock();
}
BOOL SingleLock::IsLocked()
{
	return m_bAcquired; 
}
BOOL SingleLock::Lock(DWORD dwTimeOut /* = INFINITE */)
{
	ASSERT(m_pObject != NULL || m_hObject != NULL);
	ASSERT(!m_bAcquired);

	m_bAcquired = m_pObject->Lock(dwTimeOut);
	return m_bAcquired;
}

BOOL SingleLock::Unlock()
{
	ASSERT(m_pObject != NULL);
	if (m_bAcquired)
		m_bAcquired = !m_pObject->Unlock();

	// successfully unlocking means it isn't acquired
	return !m_bAcquired;
}

BOOL SingleLock::Unlock(LONG lCount, LPLONG lpPrevCount /* = NULL */)
{
	ASSERT(m_pObject != NULL);
	if (m_bAcquired)
		m_bAcquired = !m_pObject->Unlock(lCount, lpPrevCount);

	return !m_bAcquired;
}
}